package com.common.utils.IDcreate;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

public class Utils {

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 生成指定位数的随机字符串（数字+英文） 方法名：getStringRandom 功能说明：TODO
     *
     * @Title: getStringRandom
     * @param length
     * @return
     * @author 李庆
     * @date 2015-9-21 下午03:49:42
     */
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        // 参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * md5加密
     */
    public static String md5(String source) {

        StringBuffer sb = new StringBuffer(32);

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes("UTF-8"));

            for (int i = 0; i < array.length; i++) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
        } catch (Exception e) {
            return "";
        }
        return sb.toString();
    }

    public static String map2Xml(Map<String, Object> map) {
        StringBuffer xml = new StringBuffer("<xml>");
        for (Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // if(value instanceof Number){
            // xml.append("<"+key+">"+value+"</"+key+">");
            // }else{
            xml.append("<" + key + ">" + value + "</" + key + ">");
            // }
        }
        xml.append("</xml>");
        return xml.toString();
    }

    public static boolean isNullOrEmpty(String str) {
        if (str == null || "".equals(str.trim()) || "null".equalsIgnoreCase(str.trim()) || "undefined".equalsIgnoreCase(str.trim())) {
            return true;
        } else {
            return false;
        }
    }
}
